//
//  XLOAuthViewController.swift
//  SinaProjectTest
//
//  Created by zhanghaifeng on 16/10/23.
//  Copyright © 2016年 BBSWaitting. All rights reserved.
//

import UIKit
import YYModel
import SVProgressHUD

class XLOAuthViewController: UIViewController {
    
    override func loadView() {
        view = webView
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()

    }
    
    // MARK: 监听事件
    // 取消
    @objc private func cancelClick(){
        
        SVProgressHUD.dismiss()
        dismiss(animated: true, completion: nil)
        
    }
    // 自动填充
    @objc private func autoFillClick(){
//        print("自动填充按钮被点击了")
        let jsString = "document.getElementById('userId').value='\(XLNAME)',document.getElementById('passwd').value='\(XLPASSWD)'"
        // JS 注入
        webView.stringByEvaluatingJavaScript(from: jsString)
        
    }
    private func setupUI(){
        view.backgroundColor = UIColor.white
        setupNav()
    }
    
    private func setupNav(){
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(setHighLightImageName: nil, title: "取消", target: self, action: #selector(cancelClick))
        navigationItem.rightBarButtonItem = UIBarButtonItem(setHighLightImageName: nil, title: "自动填充", target: self, action: #selector(autoFillClick))
        navigationItem.title = "微博登录"
    }
    
    // 懒加载控件
    private lazy var webView: UIWebView = {
    
        // URL 
        let url = URL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(XLAPPKEY)&redirect_uri=\(XLREDIRECTURI)")!
        // https://api.weibo.com/oauth2/authorize?client_id=298736389&redirect_uri=http://www.baidu.com
        // https://api.weibo.com/oauth2/authorize?client_id=298736389&redirect_uri=http://www.baidu.com
//        print(url)
        
        let request = URLRequest(url: url)
        let view = UIWebView()
        view.delegate = self
        view.loadRequest(request)
        return view
        
    }()

}

// MARK: UIWebView- delegate
extension XLOAuthViewController: UIWebViewDelegate{
    /*
     监听webView 将要加载的requset 默认是不实现的 返回是true
     */
    
    func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        // urlString
        let urlString = request.url?.absoluteString
        
//        print(urlString)
        // 判断urlString 不为nil 而且前缀包含我们的回调页
        if let u = urlString, u.hasPrefix(XLREDIRECTURI){
            //请求参数
            let query = request.url?.query
            if let q = query{
                // 截取到code ffa453c6617c4af30485413261f4cd4b&from=844b&vit=fps
                let code = q.substring(from: "code=".endIndex)
//                print("终于", code)
                XLUserAccountViewModel.sharedTools.getUserAccount(code: code, finish: { (isSuccess) in
                    if !isSuccess {
                        print("请求失败")
                        SVProgressHUD.showError(withStatus: "请求失败")
                        return
                    }
                    SVProgressHUD.dismiss()
                    print("请求成功")
                    self.dismiss(animated: false, completion: {
                        // 发通知跳转到欢迎界面03
                        NotificationCenter.default.post(name: NSNotification.Name(rawValue: XLSWITCHROOTVCNOTI), object: nil)
                    })
                })
                // 不在叫他加载授权界面
                return false
            }
        }
        return true
    }
    
    // 将要加载webviwe
    func webViewDidStartLoad(_ webView: UIWebView) {
        // 开始动画
        SVProgressHUD.show()
    }
    // 加载完成
    func webViewDidFinishLoad(_ webView: UIWebView) {
        // 结束动画
        SVProgressHUD.dismiss()
    }
    // 加载失败
    func webView(_ webView: UIWebView, didFailLoadWithError error: Error) {
        
    }

}
